package com.mjk.manager.task.conf;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.mjk.common.base.constns.BeeStatus;
import com.mjk.common.base.work.annotation.BeeWork;
import com.mjk.common.core.jdbc.service.log.BeeLogContentHolder;
import com.mjk.common.core.jdbc.service.log.model.BeeLogModel;
import com.mjk.common.core.jdbc.service.plus.idbservice.BaseDBService;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.scheduled.DynamicScheduledHandler;
import com.mjk.common.tools.scheduled.DynamicScheduledModel;
import com.mjk.common.tools.scheduled.annotation.BeeScheduled;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.manager.task.model.TaskModel;
import com.mjk.manager.task.type.ITaskInvoker;
import com.mjk.manager.task.type.TaskType;
import com.mjk.manager.task.type.normal.NormalTaskInvoker;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;

@Configuration
public class TaskConf extends DynamicScheduledHandler implements BeeApplicationListener {
	@Autowired
	private BaseDBService baseDBService;
	@Autowired
	private BeeLogContentHolder logService;

	/**
	 * 定义任务列表
	 */
	@Getter
	private List<DynamicScheduledModel>  tasks = new ArrayList<>();

	public void setTasks(List<DynamicScheduledModel> tasks) {
		this.tasks = tasks;
	}

	@Override
	protected List<DynamicScheduledModel> listTaskInfo() {
			return tasks;
	}

	@Override
	protected void doProcess(DynamicScheduledModel model) {
			try{
				ITaskInvoker invoker = TaskType.getTaskInvoker(model.getType());
				if(null != invoker) {
					invoker.taskInvoker(model);
				}else {//如果获取不到 调用默认得调用器
					Objects.requireNonNull(BeeSpringBean.getBean(NormalTaskInvoker.class)).taskInvoker(model);
				}
			}catch(Exception e){
				//BeeLogContentHolder.needLog.set(true);
				logService.put(new BeeLogModel(model.getId(), "3", GsonUtils.bean2Json(model), ExceptionUtil.getMessage(e)));
			}
	}	
	@Override
	public void doApplicationEvent(ContextRefreshedEvent event) {
		BeeDBService beeDBService = event.getApplicationContext().getBean(BeeDBService.class);
		Map<String, Object>  workBeans = event.getApplicationContext().getBeansWithAnnotation(BeeWork.class);
		for(Entry<String, Object> entity : workBeans.entrySet()) {
			Method[] methods = entity.getValue().getClass().getDeclaredMethods();
			for(Method m : methods) {
				BeeScheduled sd = m.getAnnotation(BeeScheduled.class);
				if(null != sd) {
					TaskModel task = new TaskModel();
					task.setTaskName(sd.scheduledName());
					task.setCorn(sd.cron());
                    task.setStatus(sd.status().getCode());
					task.setTaskInstance(entity.getValue().getClass().getName());
					task.setTaskMethod(m.getName());
					task.setTaskType(TaskType.NORMAL.getType());
					BeeQueryWrapper wrapper = new BeeQueryWrapper(task);
                    wrapper.eq(TaskModel::getTaskInstance, task.getTaskInstance()).eq(TaskModel::getTaskMethod, task.getTaskMethod());
					if (!CollectionUtils.isEmpty(beeDBService.findManyByWrapper(wrapper))) {
						//已经存在
						beeDBService.update(wrapper);
					}else {
						beeDBService.insert(task);
					}
				}
			}
		}
		BeeQueryWrapper wrapper = new BeeQueryWrapper(new TaskModel());
		List<TaskModel> taskList = beeDBService.findManyByWrapper(wrapper);
		if(!CollectionUtils.isEmpty(taskList)) {
			for(TaskModel task : taskList) {
				tasks.add(DynamicScheduledModel.builder()
						.id(task.getId()+"")
						.cron(task.getCorn())
						.type(task.getTaskType())
						.isValid(BeeStatus.RUNNING.getCode().equals(task.getStatus()))
						.taskInstance(task.getTaskInstance())
						.taskMethod(task.getTaskMethod())
						.taskParams(task.getTaskParams())
						.ext(task.getTaskContent())
						.build()
						);
			}
		}
	}

	@Override
	public int getOrder() {		
		return 99;
	}
	public void print(TaskModel dto) {
		BizLogger.info("---------------1");
	}
}
